<!--
 * @Author: 1453937336@qq.com 1453937336@qq.com
 * @Date: 2024-05-16 10:38:31
 * @LastEditors: 1453937336@qq.com 1453937336@qq.com
 * @LastEditTime: 2024-06-22 16:37:06
 * @FilePath: \itforce-hris\src\components\upload\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class=''>
    <!-- 上传附件 -->
    <a-upload
      v-if="props.fileType === 'attachment'"
      v-model:file-list="fileList"
      :before-upload="beforeUpload"
      @change="handleChange"
      @remove="handleRemove"
    >
      <slot name="content">
        <a-button type="link"><PaperClipOutlined />{{ $t('添加附件') }}</a-button>
      </slot>
    </a-upload>

    <a-upload
      class="show"
      name="file"
      v-else-if="props.fileType === 'export'"
      v-model:file-list="fileList"
      :before-upload="beforeUpload">
      <slot name="content">
        <a-button><i class="fa fa-long-arrow-alt-up"/><span style="margin-left: 4px;margin-right: 4px;">{{ $t('导入') }}</span></a-button>
      </slot>
    </a-upload>

    <a-upload
      v-else
      class="show"
      v-model:file-list="fileList"
      name="file"
      :before-upload="beforeUpload"
      @change="handleChange"
    >
      <slot name="content">
        <a-input-group compact>
          <a-input v-model:value="updateName" style="width: calc(100% - 80px)" disabled/>
          <a-button class="btn">{{ $t('浏览') }}</a-button>
        </a-input-group>
      </slot>
    </a-upload>
  </div>
</template>
<script setup>
import { useI18n } from 'vue-i18n';
const { t: $t } = useI18n();
import { message } from 'ant-design-vue';
import { Postupload, PublicExport } from '@/api/public'
import { PaperClipOutlined } from '@ant-design/icons-vue';
import { ref, reactive, toRefs, onBeforeMount, onMounted, watchEffect, computed } from 'vue';
const updateName = ref('Choose file...')
const fileList = ref([])
const fileValue = ref(null)
const emits = defineEmits(['uploadParams', 'beforeUpload', 'remove', 'refresh'])
const props = defineProps({
  fileName: {
    required: true,
    type: String,
    default: () => '',
  },
  isShow: {
    required: true,
    type: Boolean,
    default: () => false,
  },
  fileType: {
    required: true,
    type: String,
    default: () => 'default',
  },
  pageName: {
    required: true,
    type: String,
    default: () => 'organizatioin',
  },
  enterpriseId: {
    required: true,
    type: String,
    default: () => '',
  }
})
watch(() => props.fileName,
  (newVal) => {
    updateName.value = newVal
  },
  {
    flush: 'post',
  }
);

const enterpriseId = ref('')
watch(() => props.enterpriseId,
  (newVal) => {
    enterpriseId.value = newVal
  },
  {
    flush: 'post',
    deep: true,
    immediate: true
  }
);

const ApiUrl = {
  'organizatioin': '/itf/organization/web/business_unit/organization/import',
  'employee': '/itf/employee/web/employee/import'
}

const handleChange = () => {
  // if (info.file.status !== 'uploading') {
  //   // consolelog(info.file, info.fileList);
  // }
  // if (info.file.status === 'done') {
  //   message.success(`${info.file.name} file uploaded successfully`);
  // } else if (info.file.status === 'error') {
  //   message.error(`${info.file.name} file upload failed.`);
  // }
};
let formData = new FormData();
const beforeUpload = (file) => {
  fileValue.value = file
  fileList.value = [...(fileList.value || []), file];
  console.log('fileList.value', fileList.value);
  if (props.fileType === 'attachment') {
    handleUpload()
  }else if (props.fileType === 'export') {
    const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isXlsx) return message.error('You can only upload .xlsx file!');
    handleExport()
  }else {
    updateName.value = file.name
  }
  emits('beforeUpload', file)
  return false;
};

const handleExport = async () => {
  console.log('ApiUrl[props.pageName]', ApiUrl[props.pageName]);
  formData.append('file', fileValue.value);
  formData.append('enterpriseId', enterpriseId.value);
  const { code } = await PublicExport(formData, ApiUrl[props.pageName]).finally(() => {
    formData = new FormData()
  });
  if (code === 200) {
    message.success('导入成功!')
    emits('refresh')
  }
}
const fileParams = ref(null)
const list = ref([])
const handleUpload = async () => {
  formData.append('file', fileValue.value);
  // fileList.value.forEach((file: UploadProps['fileList'][number]) => {
  //   formData.append('files', file as any);
  // });
  const { data } = await Postupload(formData)
  fileParams.value = data
  if (props.fileType === 'attachment') {
    list.value.push(data)
  }
  formData = new FormData()
  emits('uploadParams', fileParams.value)
};

const handleRemove = (row) => {
  const removeParams = list.value.filter(item => item.originalFileName !== row.originFileObj.name)
  emits('remove', removeParams)
}
defineExpose({
  handleUpload
});
</script>
<style scoped lang='scss'>
.btn {
  background-color: #eaecef;
  font-weight: bolder;
}
.show {
  :deep(.ant-upload-list-item) {
    display: none;
  }
}
::v-deep {
  .ant-upload {
    width: 100%;
  }
  // 全局样式修改回来
  .ant-input {
    color: #242424;
    border: 1px solid #dadada !important;
    // border-radius: 4px !important;
  }
  // .ant-upload-wrapper .ant-upload-list .ant-upload-list-item {
  //   display: none;
  // }
}
</style>
